import request from '@/api/request'
import { getItem, getLocalChannels, setLocalChannels } from '@/utils/storage'
import { SAVE_CHSNNELS, ALL_CHANNELS, SAVE_ARTIVEL_LIST } from './constants'
const onchangeChannel = (data) => ({ type: SAVE_CHSNNELS, data })
export const getUserChannels = () => async (dispatch) => {
  if (getItem().token) {
    const res = await request({
      url: '/v1_0/user/channels',
    })
    dispatch(onchangeChannel(res.data.data.channels))
  } else {
    const channels = getLocalChannels()
    if (channels) {
      dispatch(onchangeChannel(channels))
    } else {
      const res = await request({
        url: '/v1_0/user/channels',
      })
      dispatch(onchangeChannel(res.data.data.channels))
      setLocalChannels(res.data.data.channels)
    }
  }
}

const allChannels = (data) => ({ type: ALL_CHANNELS, data })

export const getAllChannels = () => async (dispatch) => {
  const { data } = await request({
    url: '/v1_0/channels',
  })
  dispatch(allChannels(data.data.channels))
}

export const delChannel = (id) => async (dispatch, getState) => {
  const { channels } = getState().HomeReducer
  const result = channels.filter((item) => item.id !== id)
  if (getItem().token) {
    await request({
      url: '/v1_0/user/channels/' + id,
      method: 'delete',
    })
    dispatch(onchangeChannel(result))
  } else {
    dispatch(onchangeChannel(result))
    setLocalChannels(result)
  }
}

export const addChannel = (channels) => async (dispatch, getState) => {
  const addChannels = [...getState().HomeReducer.channels, channels]
  if (getItem().token) {
    request({
      url: '/v1_0/user/channels/',
      method: 'patch',
      data: {
        channels: [channels],
      },
    })
    dispatch(onchangeChannel(addChannels))
  } else {
    dispatch(onchangeChannel(addChannels))
    setLocalChannels(addChannels)
  }
}
export const getNewListData =
  (channelId, timerstamp, loadMore = false) =>
  async (dispatch) => {
    const res = await request({
      method: 'get',
      url: '/v1_0/articles/',
      params: {
        timestamp: timerstamp,
        channel_id: channelId,
      },
    })
    dispatch(
      setArticleList({
        channelId,
        timestamp: res.data.data.pre_timestamp,
        list: res.data.data.results,
        loadMore,
      })
    )
  }

export const setArticleList = (data) => ({ type: SAVE_ARTIVEL_LIST, data })
